package com.my.article.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.my.apis.wemedia.IWemediaClient;
import com.my.article.mapper.ApArticleMapper;
import com.my.article.service.HotArticleService;
import com.my.common.constans.ArticleConstas;
import com.my.common.redis.CacheService;
import com.my.model.article.pojos.ApArticle;
import com.my.model.article.vos.HotArticleVo;
import com.my.model.common.dtos.ResponseResult;
import com.my.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    /**
     * 计算文章热点数据
     */
    @Override
    public void computeArticle() {
        //1.查询前5天的数据
        Date dateParam = DateTime.now().minusDays(50).toDate();
        List<ApArticle> articleList = apArticleMapper.findArticleListByLast5days(dateParam);

        //2.计算文章分值
        List<HotArticleVo> hotArticleVoList = computeHotArticle(articleList);

        //3.为每个频道缓存30条分值较高的数据
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 计算文章分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> articleList) {
        List<HotArticleVo> list = new ArrayList<>();

        if(articleList != null && articleList.size() > 0) {
            for (ApArticle apArticle : articleList) {
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle,hotArticleVo);
                Integer score = computeScore(apArticle);
                hotArticleVo.setScore(score);
                list.add(hotArticleVo);
            }
        }

        return list;
    }

    /**
     * 根据权重计算文章分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstas.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstas.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstas.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }

    @Autowired
    private IWemediaClient wemediaClient;
    @Autowired
    private CacheService cacheService;
    /**
     * 为每个频道缓存30条分值较高的文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //获取频道信息
        ResponseResult responseResult = wemediaClient.getChannels();
        if(responseResult.getCode().equals(200)) {
            String channelJSON = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(channelJSON, WmChannel.class);
            if(wmChannels != null && wmChannels.size() > 0) {
                for (WmChannel wmChannel : wmChannels) {
                    //过滤文章，只留下属于该频道的文章数据
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(x -> x.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());
                    //对文章进行排序，选取30条分值较高的存入redis，
                    sortAndCache(ArticleConstas.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId(),hotArticleVos);
                }
            }
        }

        //设置推荐数据
        sortAndCache(ArticleConstas.HOT_ARTICLE_FIRST_PAGE + ArticleConstas.DEFAULT_TAG, hotArticleVoList);
    }

    /**
     * 排序并缓存数据
     * @param key
     * @param hotArticleVos
     */
    private void sortAndCache(String key,List<HotArticleVo> hotArticleVos) {
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        //截取前30条
        if(hotArticleVos.size() > 30) {
            hotArticleVos = hotArticleVos.subList(0,30);
        }
        cacheService.set(key,JSON.toJSONString(hotArticleVos));
    }
}
